<template>
  <van-nav-bar
    title="个人信息"
    left-arrow
    @click-left="onClickLeft"
    fixed
    placeholder
    safe-area-inset-top
  />
  <div class="personDetalsBox">
    <van-cell-group inset>
      <van-cell title="昵称" :value="userList.name" />
      <van-cell title="账号" :value="userList.account" />
      <van-cell title="身份">
        <template #value>
          <span class="custom-title" v-if="identity == 0">游客</span>
          <span class="custom-title" v-if="identity == 1">商户</span>
          <span class="custom-title" v-if="identity == 2">二级账户</span>
        </template>
      </van-cell>
      <van-cell title="注册时间" :value="userList.createTime" />
      <van-cell title="最近登录时间" :value="userList.loginTime" />
    </van-cell-group>
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { getIdentity, getUserid, setIdentity } from "@/utils/auth";
import { getuserInfo } from "@/api/login";
const identity = ref(getIdentity());
const userList = ref({});

onMounted(() => {
  getuserinfo(); //获取用户信息
});
// 获取用户信息
const getuserinfo = async () => {
  try {
    const userId = {
      userId: getUserid(), // 从本地存储中获取用户ID
    };
    const response = await getuserInfo(userId); // 调用接口获取用户信息
    const formattedRecords = response.data; // 格式化时间
    // 格式化时间
    userList.value = {
      ...formattedRecords,
      loginTime: formatISODate(formattedRecords.loginTime),
    };
    identity.value = response.data.identity; // 身份
    localStorage.setItem("userInfo", JSON.stringify(response.data)); // 用户信息保存到localStorage
    setIdentity(response.data.identity); // 身份保存到localStorage
  } catch (err) {
    //console.error('获取数据失败', err);
  }
};

// 点击返回按钮
const onClickLeft = () => history.back();

// 时间格式化工具函数
const formatISODate = (isoString) => {
  // 修复格式问题：将 "+0000" 转成 "+00:00"
  if (!isoString) return "-"; // 处理空值
  try {
    const fixedDateString = isoString.replace(/(\+\d{2})(\d{2})$/, "$1:$2");
    const date = new Date(fixedDateString);
    // 转为本地时间并格式化为 "YYYY-MM-DD HH:mm:ss"
    return date
      .toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: false, // 强制 24 小时制
      })
      .replace(/\//g, "-"); // 将斜杠替换为短横线（2025-02-23）
  } catch {
    return "-"; // 解析失败时返回占位符
  }
};
</script>

<style scoped lang="scss">
.personDetalsBox {
  margin-top: 1em;
}
</style>
